package com.example.book.service.impl;

import com.example.book.dao.BookDao;
import com.example.book.dao.OrderDao;
import com.example.book.dao.OrderItemDao;
import com.example.book.dao.impl.BookDaoImpl;
import com.example.book.dao.impl.OrderDaoImpl;
import com.example.book.dao.impl.OrderItemDaoImpl;
import com.example.book.pojo.*;
import com.example.book.service.OrderService;

import java.util.Date;
import java.util.Map;

/**
 * @Description
 * @ClassName OrderService
 * @Author 山山大魔王
 * @Date 2021/12/4 17:39
 * @Version 1.0
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();
    @Override
    public String createOrder(Cart cart, Integer userId) {

        System.out.println("OrderServiceImpl程序在["+Thread.currentThread().getName()+"]中");

        //订单号唯一
        String orderId = System.currentTimeMillis()+""+userId;
        //创建一个订单对象
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);
        //保存订单
        orderDao.saveOrder(order);
        //遍历购物车中每一个商品项转换成为订单项保存到数据库
        for (Map.Entry<Integer, CartItem> entry:cart.getItems().entrySet()){
            //获取每一个购物车中的商品项
            CartItem cartItem = entry.getValue();
            //转换为每一个订单项
            OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalPrice(), orderId);
            //保存订单项到数据库ca
            orderItemDao.saveOrderItem(orderItem);

            Book book = bookDao.queryBookById(cartItem.getId());

            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock()-cartItem.getCount());

            bookDao.updateBook(book);

        }

        cart.clear();

        return orderId;
    }
}
